<template>
  <div class="goods-detail-container">
    <el-card class="goods-detail-card" v-loading="loading">
      <div slot="header" class="clearfix">
        <el-page-header @back="goBack" content="商品详情"></el-page-header>
      </div>
      
      <el-row :gutter="20" class="action-row">
        <el-col :span="8">
          <account-selector v-model="selectedAccount" />
        </el-col>
        <el-col :span="16">
          <el-button type="primary" @click="refreshGoodsDetail" icon="el-icon-refresh">刷新</el-button>
          <el-button type="success" @click="$router.push('/goods')">返回列表</el-button>
        </el-col>
      </el-row>
      
      <div class="goods-info" v-if="goods">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="ID">{{ goods.id }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{ goods.name }}</el-descriptions-item>
          <el-descriptions-item label="描述">{{ goods.description }}</el-descriptions-item>
          <el-descriptions-item label="当前所有者">
            <el-tag type="success">{{ getAccountNameByAddress(goods.owner) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTimestamp(goods.createTime) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="left">所有权转移历史</el-divider>
        
        <el-timeline>
          <el-timeline-item
            v-for="(owner, index) in goods.historyOwners"
            :key="index"
            :timestamp="formatTimestamp(goods.ownershipTimestamps && goods.ownershipTimestamps[index] ? goods.ownershipTimestamps[index] : '')"
            :type="index === goods.historyOwners.length - 1 ? 'primary' : ''"
            :color="index === goods.historyOwners.length - 1 ? '#409EFF' : ''">
            <el-card class="timeline-card">
              <div class="address-info">
                <span>所有者: </span>
                <el-tag size="medium">{{ getAccountNameByAddress(owner) }}</el-tag>
                <span v-if="index === 0" class="owner-label">(创建者)</span>
                <span v-else-if="index === goods.historyOwners.length - 1" class="owner-label">(当前所有者)</span>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        
        <el-divider></el-divider>
        
        <div class="action-buttons">
          <el-button type="primary" @click="editGoods" icon="el-icon-edit"
            :disabled="!isCurrentUserOwner(goods.owner)">编辑商品</el-button>
          <el-button type="success" @click="showTransferDialog" icon="el-icon-position"
            :disabled="!isCurrentUserOwner(goods.owner)">转移所有权</el-button>
          <el-button type="danger" @click="confirmDelete" icon="el-icon-delete"
            :disabled="!isCurrentUserOwner(goods.owner)">删除商品</el-button>
        </div>
      </div>
      
      <el-empty v-else description="未找到商品信息"></el-empty>
      
      <!-- 编辑商品对话框 -->
      <el-dialog title="编辑商品" :visible.sync="editDialogVisible" width="40%">
        <el-form :model="goodsForm" label-width="80px" :rules="rules" ref="editForm">
          <el-form-item label="ID">
            <el-input v-model="goodsForm.goodsId" disabled></el-input>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="goodsForm.name"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input type="textarea" v-model="goodsForm.description"></el-input>
          </el-form-item>
          <el-form-item label="账户">
            <el-select v-model="goodsForm.account" placeholder="选择账户" style="width: 100%">
              <el-option
                v-for="(address, name) in filteredAccounts"
                :key="name"
                :label="`${name} (${address.substring(0, 8)}...)`"
                :value="name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateGoods">确定</el-button>
        </span>
      </el-dialog>
      
      <!-- 转移商品对话框 -->
      <el-dialog title="转移商品" :visible.sync="transferDialogVisible" width="40%">
        <el-form :model="transferForm" label-width="120px" :rules="transferRules" ref="transferForm">
          <el-form-item label="商品ID">
            <el-input v-model="transferForm.goodsId" disabled></el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="transferForm.name" disabled></el-input>
          </el-form-item>
          <el-form-item label="当前所有者">
            <el-input :value="getAccountNameByAddress(transferForm.currentOwner)" disabled></el-input>
          </el-form-item>
          <el-form-item label="转移到" prop="to">
            <el-select v-model="transferForm.to" placeholder="选择接收者账户" style="width: 100%" filterable>
              <el-option
                v-for="(address, name) in filteredAccounts"
                :key="`to-${name}`"
                :label="`${name} (${address.substring(0, 8)}...)`"
                :value="address">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="transferDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="transferGoods">确定</el-button>
        </span>
      </el-dialog>
      
      <!-- 交易结果对话框 -->
      <el-dialog title="交易详情" :visible.sync="txDialogVisible" width="50%" center>
        <div class="tx-result-container">
          <el-result
            :icon="txResult.success ? 'success' : 'error'"
            :title="txResult.title"
            :sub-title="txResult.message">
            <template slot="extra">
              <div class="tx-details" v-if="txResult.success">
                <el-descriptions border :column="1">
                  <el-descriptions-item label="交易哈希">
                    <el-tag type="info" effect="plain">{{ txResult.txHash }}</el-tag>
                    <el-button type="text" size="mini" @click="copyToClipboard(txResult.txHash)">
                      <i class="el-icon-document-copy"></i> 复制
                    </el-button>
                  </el-descriptions-item>
                  <el-descriptions-item v-if="txResult.extraInfo" label="其他信息">
                    {{ txResult.extraInfo }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
              <el-button type="primary" @click="txDialogVisible = false">确定</el-button>
            </template>
          </el-result>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { goodsApi, formatTimestamp, handleApiError, BLOCKED_ACCOUNTS } from '@/utils/api'
import { mapState } from 'vuex'
import AccountSelector from '@/components/AccountSelector.vue'

export default {
  name: 'GoodsDetail',
  components: {
    AccountSelector
  },
  data() {
    return {
      loading: false,
      goodsId: '',
      editDialogVisible: false,
      transferDialogVisible: false,
      txDialogVisible: false,
      txResult: {
        success: false,
        title: '',
        message: '',
        txHash: '',
        extraInfo: null
      },
      goodsForm: {
        name: '',
        description: '',
        account: '',
        goodsId: ''
      },
      transferForm: {
        goodsId: '',
        name: '',
        currentOwner: '',
        to: '',
        account: ''
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }]
      },
      transferRules: {
        to: [{ required: true, message: '请选择接收者账户', trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapState(['accounts', 'currentGoods', 'selectedAccount']),
    
    goods() {
      return this.currentGoods
    },
    
    // 选择账户的计算属性，支持双向绑定
    selectedAccount: {
      get() {
        return this.$store.state.selectedAccount
      },
      set(value) {
        this.$store.commit('setSelectedAccount', value)
        this.refreshGoodsDetail()
      }
    },
    
    // 过滤掉特定账户
    filteredAccounts() {
      // 不再过滤任何账户，直接返回所有账户
      const filtered = {...this.accounts};
      // 如果仍需要使用BLOCKED_ACCOUNTS，可以保留以下逻辑，但由于现在是空数组所以不会过滤掉任何账户
      BLOCKED_ACCOUNTS.forEach(address => {
        delete filtered[address];
      });
      
      console.log('显示所有账户:', Object.keys(filtered).length);
      return filtered;
    }
  },
  created() {
    this.goodsId = this.$route.params.id
    this.initData()
  },
  methods: {
    formatTimestamp,
    
    async initData() {
      try {
        this.loading = true
        await this.$store.dispatch('fetchAccounts')
        if (this.goodsId) {
          await this.refreshGoodsDetail()
        }
      } catch (error) {
        handleApiError(error)
      } finally {
        this.loading = false
      }
    },
    
    async refreshGoodsDetail() {
      if (!this.selectedAccount || !this.goodsId) return
      
      try {
        this.loading = true
        console.log('刷新商品详情，ID:', this.goodsId, '类型:', typeof this.goodsId)
        // 将路由参数转换为数字，确保ID为0的商品能正确处理
        const numericId = parseInt(this.goodsId)
        await this.$store.dispatch('fetchGoodsDetail', numericId)
        
        // 如果加载完成后没有商品数据，显示错误信息
        if (!this.currentGoods) {
          this.$message.error(`未找到ID为${this.goodsId}的商品信息`)
        } else {
          // 打印所有者信息和历史用于调试
          console.log('商品当前所有者:', this.currentGoods.owner)
          console.log('历史所有者列表:', this.currentGoods.historyOwners)
          console.log('所有权时间戳:', this.currentGoods.ownershipTimestamps)
        }
      } catch (error) {
        handleApiError(error)
      } finally {
        this.loading = false
      }
    },
    
    goBack() {
      this.$router.back()
    },
    
    editGoods() {
      if (!this.goods) return
      
      // 检查当前用户是否是商品所有者
      if (!this.isCurrentUserOwner(this.goods.owner)) {
        this.$message.warning('只有商品所有者才能编辑商品');
        return;
      }
      
      this.goodsForm = {
        goodsId: this.goods.id,
        name: this.goods.name,
        description: this.goods.description,
        account: this.selectedAccount
      }
      this.editDialogVisible = true
      this.$nextTick(() => {
        this.$refs.editForm && this.$refs.editForm.clearValidate()
      })
    },
    
    async updateGoods() {
      try {
        await this.$refs.editForm.validate()
        
        this.loading = true
        const response = await goodsApi.updateGoods(this.goodsForm)
        
        if (response.data.success) {
          // 显示成功对话框和交易哈希
          this.showTxResult({
            success: true,
            title: '更新商品成功',
            message: `商品 "${this.goodsForm.name}" 已更新`,
            txHash: response.data.txHash || '未返回交易哈希'
          })
          this.editDialogVisible = false
          this.refreshGoodsDetail()
        } else {
          this.showTxResult({
            success: false,
            title: '更新商品失败',
            message: response.data.message || '操作失败'
          })
        }
      } catch (error) {
        handleApiError(error)
      } finally {
        this.loading = false
      }
    },
    
    showTransferDialog() {
      if (!this.goods) return
      
      // 检查当前用户是否是商品所有者
      if (!this.isCurrentUserOwner(this.goods.owner)) {
        this.$message.warning(`只有商品所有者才能转移商品。当前所有者: ${this.getAccountNameByAddress(this.goods.owner)}`);
        return;
      }
      
      this.transferForm = {
        goodsId: this.goods.id,
        name: this.goods.name,
        currentOwner: this.goods.owner,
        to: '',
        account: this.selectedAccount
      }
      this.transferDialogVisible = true
      this.$nextTick(() => {
        this.$refs.transferForm && this.$refs.transferForm.clearValidate()
      })
    },
    
    async transferGoods() {
      try {
        await this.$refs.transferForm.validate()
        
        this.loading = true
        // 确保transferForm中的currentOwner是商品的最新所有者
        this.transferForm.currentOwner = this.goods.owner
        
        console.log('发送转移请求:', {
          goodsId: this.transferForm.goodsId,
          to: this.transferForm.to,
          account: this.transferForm.account,
          currentOwner: this.transferForm.currentOwner
        })
        
        const response = await goodsApi.transferGoods(this.transferForm)
        
        if (response.data.success) {
          // 显示成功对话框和交易哈希
          const receiverName = this.getAccountNameByAddress(this.transferForm.to);
          this.showTxResult({
            success: true,
            title: '转移商品成功',
            message: `商品 "${this.transferForm.name}" 已转移给 ${receiverName}`,
            txHash: response.data.txHash || '未返回交易哈希',
            extraInfo: `接收者: ${receiverName}`
          })
          this.transferDialogVisible = false
          // 等待1秒后刷新数据，确保区块链数据已更新
          setTimeout(() => {
            this.refreshGoodsDetail()
          }, 1000)
        } else {
          this.showTxResult({
            success: false,
            title: '转移商品失败',
            message: response.data.message || '操作失败'
          })
        }
      } catch (error) {
        handleApiError(error)
      } finally {
        this.loading = false
      }
    },
    
    confirmDelete() {
      if (!this.goods) return
      
      // 检查当前用户是否是商品所有者
      if (!this.isCurrentUserOwner(this.goods.owner)) {
        this.$message.warning('只有商品所有者才能删除商品');
        return;
      }
      
      this.$confirm('确定要删除该商品吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.removeGoods()
      }).catch(() => {})
    },
    
    async removeGoods() {
      try {
        this.loading = true
        const response = await goodsApi.removeGoods({
          goodsId: this.goods.id,
          account: this.selectedAccount
        })
        
        if (response.data.success) {
          // 显示成功对话框和交易哈希
          this.showTxResult({
            success: true,
            title: '删除商品成功',
            message: `商品ID ${this.goods.id} 已成功删除`,
            txHash: response.data.txHash || '未返回交易哈希'
          })
          // 等待用户确认后再跳转
          this.$once('tx-dialog-closed', () => {
            this.$router.push('/goods')
          })
        } else {
          this.showTxResult({
            success: false, 
            title: '删除商品失败',
            message: response.data.message || '操作失败'
          })
        }
      } catch (error) {
        handleApiError(error)
      } finally {
        this.loading = false
      }
    },
    
    // 根据地址获取账户名称
    getAccountNameByAddress(address) {
      if (!this.accounts || !address) return '未知账户';
      
      // 遍历accounts对象，查找匹配的地址
      for (const [name, addr] of Object.entries(this.accounts)) {
        if (addr === address) {
          return name;
        }
      }
      
      // 如果没找到匹配的账户名，返回地址的简短形式
      return address.substring(0, 8) + '...';
    },
    
    // 判断当前用户是否是商品所有者
    isCurrentUserOwner(owner) {
      if (!this.accounts || !this.selectedAccount || !owner) {
        console.warn('无法验证所有权: 账户信息不完整或所有者为空', 
                    {accounts: this.accounts, selectedAccount: this.selectedAccount, owner: owner});
        return false;
      }
      
      const currentAddress = this.accounts[this.selectedAccount];
      
      // 获取账户名对应的地址
      let nameOfOwner = '';
      for (const [name, addr] of Object.entries(this.accounts)) {
        if (addr.toLowerCase() === owner.toLowerCase()) {
          nameOfOwner = name;
          break;
        }
      }
      
      // 添加调试信息，包括所有者的账户名
      console.log('所有权检查:', {
        owner: owner, // 商品所有者地址
        ownerAccountName: nameOfOwner || '未知账户', // 所有者对应的账户名
        currentAddress: currentAddress, // 当前选中的用户地址
        selectedAccount: this.selectedAccount, // 当前选中的账户名
        isOwner: owner.toLowerCase() === currentAddress.toLowerCase() // 不区分大小写比较
      });
      
      // 使用不区分大小写的比较
      return owner.toLowerCase() === currentAddress.toLowerCase();
    },
    
    // 显示交易结果对话框
    showTxResult(result) {
      this.txResult = result
      this.txDialogVisible = true
      
      // 监听对话框关闭事件
      const handleClose = () => {
        this.$emit('tx-dialog-closed')
        this.$off('tx-dialog-closed', handleClose)
      }
      this.$on('tx-dialog-closed', handleClose)
    },
    
    // 复制文本到剪贴板
    copyToClipboard(text) {
      const textarea = document.createElement('textarea')
      textarea.value = text
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      this.$message.success('已复制到剪贴板')
    }
  }
}
</script>

<style scoped>
.goods-detail-container {
  padding: 20px;
}

.goods-detail-card {
  width: 100%;
}

.action-row {
  margin-bottom: 20px;
}

.goods-info {
  margin-top: 20px;
}

.timeline-card {
  margin-bottom: 10px;
}

.address-info {
  display: flex;
  align-items: center;
}

.owner-label {
  margin-left: 10px;
  color: #909399;
  font-style: italic;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style> 